package com.cloud.service;

import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.cloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.cloud.bean.User;
import com.cloud.mapper.UserMapper;

@Service
public class LoginService {
	private static final Logger log = LoggerFactory.getLogger(LoginService.class);
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Resource
	private UserMapper userMapper;
	/**
	 * 登陆验证
	 * @param params
	 * @return
	 */
	public R login(JSONObject params, HttpServletRequest request, HttpServletResponse response) {
		Boolean isAdmin = params.getBoolean("isAdmin");
		String phone = params.getString("phone");
		String password = params.getString("password");
		JSONObject result;
		if (isAdmin){
			result = userMapper.selectAdminByPhone(phone);
			if (result == null){
				return new R(1,"用户账号或密码错误",null);
			}
		}else {
			User user = userMapper.selectByPhone(phone);
			if(user == null) {
				return new R(1,"用户账号或密码错误",null);
			}
			Object o = JSONObject.toJSON(user);
			result = JSONObject.parseObject(o.toString());
		}

		String pwd = "";
		try {
			pwd = SecUtil.MD5(password);
		} catch (Exception e) {
			log.error("用户密码MD5出错");
			e.printStackTrace();
			return R.error("密码格式错误");
		}
		if(!pwd.equals(result.getString("password"))) {
			return R.error("用户账号或密码错误");
		}
		if (isAdmin){
			CookieUtil.setCookie(request, response, "DSG_ADMIN", phone, true);
		}else {
			CookieUtil.setCookie(request, response, "DSG_USER", phone, true);
		}
		result.remove("password");
		redisUtil.set(phone,result,120);
		return R.ok(result);
	}
	/**
	 * 设置验证码到redis,保存60秒
	 * @return
	 */
	public R getCode(String phone) {
		VerifyCodeUtil verify = new VerifyCodeUtil();
		String encode = verify.drawImage();
		String code = verify.getCode();
		boolean setnx = redisUtil.setnx("CODE_"+phone, code, 60);
		log.info("验证码="+code+" setnx="+setnx);
		return new R(0,"验证码获取成功，有效时长60秒",encode);
	}
	/**
	 * 注册
	 * @param params
	 * @return
	 */
	public R register(JSONObject params, HttpServletRequest request) {
		String phone = params.getString("phone");
		String username = params.getString("username");
		String password = params.getString("password");
		String invitationCode = params.getString("invitationCode");
		User user = userMapper.selectByPhone(phone);
		if(user != null) {
			return R.error("用户已存在");
		}
		try {
			password = SecUtil.MD5(password);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("用户密码MD5出错");
			return R.error("密码格式错误");
		}
		user = new User();
		synchronized (LoginService.class) {
			if(StringUtils.hasLength(invitationCode)) {
				User oldUser = userMapper.selectByInvitationcode(invitationCode);
				if(oldUser == null) {
					return R.error("邀请码不存在");
				}else {
					user.setPid(Integer.parseInt(invitationCode));
					user.setInvitationcode("0");
				}
			}else {
				String last = userMapper.selectOrderByInvitationcode();
				user.setInvitationcode(YQMUtils.getString(1,last));
				user.setPid(0);
			}
		}
		user.setPhone(phone);
		user.setUsername(username);
		user.setPassword(password);
		user.setViplevel(1);
		user.setAgentlevel(1);
		user.setCreatetime(DateFormatUtils.formatDate(new Date(), "yyyy-MM-dd"));
		user.setStatus(0);
		user.setLoginip(request.getRemoteAddr());
		user.setBalance(0d);
		user.setUpdatetime(DateFormatUtils.formatDate(new Date(), "yyyy-MM-dd"));
		userMapper.insert(user);
		return R.ok();
	}

	public void loginout(JSONObject params){
		redisUtil.del(params.getString("phone"));
	}
}
